package other.xsy.passlys.account;

import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEventResponse;
import com.rkhd.platform.sdk.data.model.Account;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.QueryResult;
import com.rkhd.platform.sdk.model.XObject;
import com.rkhd.platform.sdk.service.XoqlService;
import com.rkhd.platform.sdk.trigger.DataResult;
import com.rkhd.platform.sdk.trigger.Trigger;
import com.rkhd.platform.sdk.trigger.TriggerRequest;
import com.rkhd.platform.sdk.trigger.TriggerResponse;
import other.xsy.passlys.util.CustomAdminUtil;
import other.xsy.passlys.util.HCXObjectService;
import other.xsy.passlys.util.HcUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description 新增客户前 判断是否重复
 * @Author 黎炎松
 * 2024-06-12 15:13
 */
public class
AccountAddBeforeTrigger implements Trigger {

    private static final Logger logger = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "新增客户进行是否重复判断 ==> ";

    @Override
    public TriggerResponse execute(TriggerRequest request) throws ScriptBusinessException {
        logger.debug(LOGGER_MSG + " 触发开始 ");
        List<XObject> dataList = request.getDataList();
        List<DataResult> dataResultList = new ArrayList<>();
        List<Account> accountList = new ArrayList<>();
        for (XObject xObject : dataList) {
            Account account = (Account) xObject;
            accountList.add(account);
            dataResultList.add(new DataResult(true, "", xObject));
        }
        dataResultList.set(0, accountIsExist(accountList.get(0)));
        return new TriggerResponse(true, "处理完成", dataResultList);
    }

    public static void main(String[] args) throws ApiEntityServiceException {
        Account account = new Account();
        account.setAccountName("上海迈谛科技有限公司");
        account.setOwnerId(3380875185363547L);
        new AccountAddBeforeTrigger().accountIsExist(account);
    }


    /**
     * 客户重复判断
     * @param account
     */
    public DataResult accountIsExist(Account account){
        try {
            logger.info(LOGGER_MSG + " 处理开始:" + account);
            String accountName = account.getAccountName(); // 客户名称 accountName
            Long ownerId = account.getOwnerId(); // 所有人

            // 判断一：客户名称 + 报备状态（3 报备通|| 5 无需报备） 提示信息：该客户已报备通过，无需报备，客户所属团队：(所属部门）,所有人：(所有人)，业务类型：（业务类型）
            String sql = "select id,dimDepart.departName departName,ownerId.name ownerName,customerType__c,entityType " +
                    "from account where (reportingStatus__c = 3 or reportingStatus__c = 5) and accountName = '" + accountName + "'";
            QueryResult<JSONObject> query = CustomAdminUtil.sendAdminXoqlQuery(sql);
            if (!query.getSuccess()) {
                logger.error(LOGGER_MSG + " 查询异常");
                return new DataResult(false, "查询异常", account);
            }

            logger.info(LOGGER_MSG + " query:" + query.getRecords());
            if (query.getTotalCount() > 0) {
                // 获取参数
                List<JSONObject> searchAccountList = query.getRecords();
                JSONObject searchAccount = searchAccountList.get(0);
                String departName = searchAccount.getString("departName"); // 部门名称
                String ownerName = searchAccount.getString("ownerName"); // 所有人

                // 获取业务类型
                Long entityType = searchAccount.getLong("entityType");
                String entityName = "";
                JSONObject accountEntityJson = HcUtils.getEntityApiKey("account", entityType);
                if (accountEntityJson != null) {
                    entityName = accountEntityJson.getString("label");
                }

                // 获取提示语
                String msg = "该客户已报备通过，无需报备，客户所属团队:(%s),所有人:(%s),业务类型:(%s)。";
                msg = String.format(msg, departName, ownerName, entityName);
                logger.info(LOGGER_MSG + msg);
                return new DataResult(false, msg, account);
            }

            // 判断二：客户名称 + 报备状态 + 所有人  提示信息：该客户您已创建，无需再创建，请更新客户信息并提交客户报备。
            sql = "select id from account where (reportingStatus__c != 3 or reportingStatus__c is null) and ownerId =" + ownerId + " and accountName = '" + accountName + "'";
            QueryResult<JSONObject> towQuery = CustomAdminUtil.sendAdminXoqlQuery(sql);
            logger.info(LOGGER_MSG + " twoSearchAccount:" + towQuery.getRecords());
            if (towQuery.getSuccess() && towQuery.getRecords().size() > 0) {
                logger.error(LOGGER_MSG + " 该客户您已创建，无需再创建，请更新客户信息并提交客户报备。");
                return new DataResult(false,"该客户您已创建，无需再创建，请更新客户信息并提交客户报备。", account);
            }

            // 判断NA客户上限
            CheckAddAccountCount checkAddAccountCount = new CheckAddAccountCount();
            ApprovalEventResponse approvalEventResponse = checkAddAccountCount.checkAccountCounts(account);
            if (!approvalEventResponse.getSuccess()) {
                // 已达上限，不允许新增
                String msg = approvalEventResponse.getMsg();
                logger.debug(LOGGER_MSG + msg);
                return new DataResult(false, msg, account);
            }

            // 允许创建
            logger.info(LOGGER_MSG + " 客户不存在，允许创建客户");
            return new DataResult(true,"" , account);
        } catch (Exception e) {
            logger.error(LOGGER_MSG + " 处理异常:" + e.getMessage());
            return new DataResult(false, "处理异常:" + e.getMessage(), account);
        }
    }


}
